package com.cskaoyan;

import org.apache.commons.dbcp.BasicDataSourceFactory;

import javax.sql.DataSource;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Properties;

/**
 * 创建日期: 2022/10/10 17:19
 *
 * @author ciggar
 */
public class DBCPUtils {

    static DataSource dataSource;


    static {

//        BasicDataSource basicDataSource = new BasicDataSource();

//        basicDataSource.setUsername();
//        basicDataSource.setUrl();
//        basicDataSource.setPassword();
//        basicDataSource.setConnectionProperties();
//
//
//        basicDataSource.setInitialSize();
//        basicDataSource.setMaxIdle();
//        basicDataSource.setMinIdle();
//        basicDataSource.setMaxWait();

        try {
            Properties properties = new Properties();
//            properties.load(new FileInputStream("target/classes/dbcp.properties"));


            // RootClassLoader
            // ExtensionClassLoader
            // AppClassloader

            // 通过类加载器找classes路径下的配置文件
            ClassLoader classLoader = DatasourceDemo.class.getClassLoader();
            InputStream in = classLoader.getResourceAsStream("dbcp.properties");


//            String path = classLoader.getResource("dbcp.properties").getPath();
//
//            System.out.println("path:" + path);
//            FileInputStream fileInputStream = new FileInputStream(path);

            properties.load(in);


            dataSource = BasicDataSourceFactory.createDataSource(properties);

        }catch (Exception ex) {
            ex.printStackTrace();
        }

    }


    // 获取DBCP数据库连接池创建的连接
    public static Connection getConnection(){

        Connection connection = null;
        try {
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return connection;

    }
}
